<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkMessage\Action\Dashboard\Config;

use Hyperf\Contract\ConfigInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\App\WorkMessage\Action\Dashboard\Config\Traits\RequestTrait;
use MoChat\App\WorkMessage\Contract\WorkMessageConfigContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 修改 - 页面.
 * @Controller
 */
class StepUpdate extends AbstractAction
{
    use ValidateSceneTrait;
    use RequestTrait;

    /**
     * @Inject
     * @var ConfigInterface
     */
    protected $config;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/workMessageConfig/stepUpdate", methods="PUT")
     */
    public function handle(): array
    {
        $params['chatApplyStatus'] = (int) $this->request->input('chatApplyStatus', 0);
        $params['chatRsaKey'] = $this->request->input('chatRsaKey');
        $params['chatSecret'] = $this->request->input('chatSecret');
        $params['chatStatus'] = $this->request->input('chatStatus', 1); // (会话内容)存档状态 0不存储 1存储

        $messageConfigService = $this->container->get(WorkMessageConfigContract::class);
        $info = $messageConfigService->getWorkMessageConfigByCorpId(user('corpIds')[0], ['id', 'chat_rsa_key']);

        $data['chat_apply_status'] = $params['chatApplyStatus'];
        // 第三步骤
        if ($params['chatApplyStatus'] === 3) {
            $this->validated($params, 'stepThird');
            $data['corp_id'] = user('corpIds')[0];
            // 公钥、私钥、版本号处理，原数据一维数组改二维数组，版本号相同，不修改
            $chatRsaKey = $this->handleChatRsaKey($params['chatRsaKey'], $info);
            $data['chat_rsa_key'] = Json::encode($chatRsaKey);
        } elseif ($params['chatApplyStatus'] === 4) {
            // 第四步骤
            $data['chat_secret'] = $params['chatSecret'];
            $this->validated($params, 'stepFour');
        } elseif ($params['chatApplyStatus'] === 6) {
            // 第六步骤
            $data['chat_apply_status'] = 4;
            $data['chat_status'] = $params['chatStatus'];
        } else {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '申请进度错误');
        }

        // 入库
        Db::beginTransaction();
        try {
            if (empty($info)) {
                $messageConfigService->createWorkMessageConfig($data);
            } else {
                // 修改动作
                $messageConfigService->updateWorkMessageConfigById($info['id'], $data);
            }

            Db::commit();
        } catch (\Throwable $ex) {
            Db::rollBack();
            throw new CommonException(ErrorCode::SERVER_ERROR, '修改失败' . $ex->getMessage());
        }
        return [];
    }

    private function handleChatRsaKey($chatRsaKey, $info): array
    {
        if (empty($chatRsaKey['version'])) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '版本号不能为空');
        }
        $data = [];
        if (! empty($info['chatRsaKey'])) {
            $infoChatRsaKey = Json::decode($info['chatRsaKey']);
            // 一维数组
            if (count($infoChatRsaKey) === count($infoChatRsaKey, 1)) {
                // 原版本号为空，或版本号未变
                if (empty($infoChatRsaKey['version']) || (int) $infoChatRsaKey['version'] === (int) $chatRsaKey['version']) {
                    return [$chatRsaKey];
                }
                // 版本号修改，追加保存
                $data[] = $infoChatRsaKey;
                $data[] = $chatRsaKey;
                return $data;
            }
            // 删除空版本号
            foreach ($infoChatRsaKey as &$item) {
                if (empty($item['version'])) {
                    unset($item);
                }
            }
            unset($item);
            $infoChatRsaKey = array_merge($infoChatRsaKey);
            // 二维数组
            $versions = array_column($infoChatRsaKey, 'version');
            // 版本号已存在
            if (in_array($chatRsaKey['version'], $versions, true)) {
                return $infoChatRsaKey;
            }
            $infoChatRsaKey[] = $chatRsaKey;
            return $infoChatRsaKey;
        }
        return [$chatRsaKey];
    }
}
